// pages/find/find.js
const server = require("../../server/server.js");
Page({

    /**
     * 页面的初始数据
     */
    data: {
        dot: true,
        products: [],
        total: 0,
        params: {
            page: 1,
            rows: 4
        },
        init: false,
        flag: true
    },
    onLoad() {
        this.loadProductList();
        this.loadTypeList();
    },
    loadProductList() {
        return server.loadProductList(this.data.params)
            .then((data) => {
                this.setData({
                    products: this.data.products.concat(data.rows),
                    total: data.total
                })
            })
            .catch((error) => {
                console.log(error);
            })
    },
    loadTypeList(){
        server.loadTypeList()
        .then((data)=>{
            // console.log(data)
            let all = {
                id: -1,
                name:"全部",
                imgUrl:"../../img/temp/all.png"
            }
            data.unshift(all);
            let temp=[];
            let size=Math.ceil(data.length / 5);
            for(let i=0;i<size;i++){
                temp.push(data.splice(0,5));
            }
            // console.log(temp);
            this.setData({
                types:temp
            });
        })
        .catch((error)=>{
            console.log(error);
        })
    },
    fintByType({ currentTarget: { dataset: { typeId } } }){
        this.setData({
            products:[],
            "params.typeId":typeId,
            "params.page":1,
            init:false
        });
        this.loadProductList();
    },
    onReachBottom() {
        this.setData({
            init: true,
            flag: true
        });
        let page = this.data.params.page + 1;
        let rows = this.data.params.rows;
        let count = Math.ceil(this.data.total / rows);
        if (page > count) {
            this.setData({
                flag: false
            });
            return;
        }
        this.setData({
            "params.page": this.data.params.page + 1
        });
        setTimeout(() => {
            this.loadProductList()
                .then(() => {
                    this.setData({
                        flag: false,
                        init: false
                    })
                })
        }, 2000);

    },
})